<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PDF转为图片型的Word</title>
    <!-- 本地引用Tailwind CSS -->
    <script src="../../assets/js/tailwind.min.js"></script>
    <style>
        .drag-drop-area {
            border: 2px dashed #cbd5e0;
            transition: all 0.3s;
        }
        .drag-drop-area.drag-over {
            border-color: #4299e1;
            background-color: #ebf8ff;
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen p-6">
    <div class="max-w-2xl w-full mx-auto bg-white rounded-xl shadow-md overflow-hidden p-6 mt-8">
        <h1 class="text-2xl font-bold text-gray-800 mb-2 flex items-center">
            <span class="mr-2">➡️</span> PDF转为图片型的Word
        </h1>
        <p class="text-sm text-gray-500 mb-6">注：此工具将PDF转换为图片格式嵌入Word，保留原始排版，适用于标书制作时需要在Word中附图片型合同等场景。</p>
        
        <div class="mb-6">
            <label class="block text-sm font-medium text-gray-700 mb-2">选择PDF文件</label>
            <div class="drag-drop-area rounded-lg p-8 text-center" id="dragDropArea">
                <input type="file" id="upload" accept="application/pdf" multiple class="hidden">
                <label for="upload" 
                    class="cursor-pointer bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg flex items-center transition-colors justify-center mx-auto w-fit">
                    <span class="mr-2">📂</span> 选择文件
                </label>
                <p class="mt-4 text-gray-500">或拖拽文件到此处</p>
                <div id="fileList" class="mt-2 text-sm text-gray-500"></div>
            </div>
        </div>
        
        <div class="mb-6">
            <button onclick="processPDF()" 
                    class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-lg flex items-center transition-colors mx-auto">
                <span class="mr-2">🔄</span> 开始转换
            </button>
        </div>
        
        <div class="progress-container bg-gray-200 rounded-full h-4 mb-6 hidden" id="progressContainer">
            <div class="progress-bar bg-blue-500 h-full rounded-full text-xs text-white flex items-center justify-center transition-all duration-300" 
                id="progressBar" style="width: 0%">0%</div>
        </div>
        
        <div id="status" class="p-4 rounded-lg hidden"></div>
    </div>

    <!-- 依赖库 -->
    <script src="../../assets/js/pdf.min.js"></script>
    <script src="../../assets/js/docx.min.js"></script>
    <script src="../../assets/js/jszip.min.js"></script>
    <script src="../../assets/js/FileSaver.min.js"></script>

    <script>
        // 设置PDF.js worker路径
        pdfjsLib.GlobalWorkerOptions.workerSrc = '../../assets/js/pdf.worker.min.js';

        let pdfFiles = []; // 存储PDF文件数组
        let pdfImages = []; // 存储转换后的图片

        // 拖拽上传功能
        const dragDropArea = document.getElementById('dragDropArea');
        const fileInput = document.getElementById('upload');

        // 拖拽事件处理
        dragDropArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            dragDropArea.classList.add('drag-over');
        });

        dragDropArea.addEventListener('dragleave', () => {
            dragDropArea.classList.remove('drag-over');
        });

        dragDropArea.addEventListener('drop', (e) => {
            e.preventDefault();
            dragDropArea.classList.remove('drag-over');
            
            if (e.dataTransfer.files.length) {
                fileInput.files = e.dataTransfer.files;
                updateFileList();
            }
        });

        // 监听文件上传事件
        fileInput.addEventListener('change', function() {
            if (this.files.length > 0) {
                updateFileList();
            }
        });

        // 更新文件列表显示
        function updateFileList() {
            const fileListDiv = document.getElementById('fileList');
            fileListDiv.innerHTML = '';
            
            if (fileInput.files.length === 0) {
                fileListDiv.textContent = '未选择文件';
                pdfFiles = [];
                return;
            }
            
            pdfFiles = Array.from(fileInput.files);
            
            const totalSize = pdfFiles.reduce((sum, file) => sum + file.size, 0);
            
            pdfFiles.forEach((file, index) => {
                const item = document.createElement('div');
                item.className = 'flex items-center mb-1';
                item.innerHTML = `
                    <span class="mr-2">📄</span>
                    <span>${file.name}</span>
                    <span class="ml-auto text-xs text-gray-400">${(file.size / 1024 / 1024).toFixed(2)} MB</span>
                `;
                fileListDiv.appendChild(item);
            });
            
            // 添加总文件数和总大小信息
            const infoItem = document.createElement('div');
            infoItem.className = 'flex items-center mt-2 text-sm font-medium text-gray-600';
            infoItem.innerHTML = `
                <span class="mr-2">📊</span>
                <span>共 ${pdfFiles.length} 个文件</span>
                <span class="ml-auto">总大小: ${(totalSize / 1024 / 1024).toFixed(2)} MB</span>
            `;
            fileListDiv.appendChild(infoItem);
        }

        async function processPDF() {
            if (pdfFiles.length === 0) return alert('请先上传 PDF 文件');
            
            // 初始化UI状态
            const progressContainer = document.getElementById('progressContainer');
            const progressBar = document.getElementById('progressBar');
            const statusDiv = document.getElementById('status');
            
            progressContainer.classList.remove('hidden');
            progressBar.style.width = '0%';
            progressBar.textContent = '0%';
            statusDiv.classList.add('hidden');
            
            try {
                // 清空之前的转换结果
                pdfImages = [];
                let totalPages = 0;
                let processedPages = 0;
                
                // 处理所有PDF文件
                for (let fileIndex = 0; fileIndex < pdfFiles.length; fileIndex++) {
                    const pdfFile = pdfFiles[fileIndex];
                    statusDiv.textContent = `正在处理文件 ${fileIndex + 1}/${pdfFiles.length}: ${pdfFile.name}`;
                    statusDiv.className = 'p-4 rounded-lg bg-blue-100 text-blue-800 border border-blue-200';
                    statusDiv.classList.remove('hidden');
                    
                    const arrayBuffer = await pdfFile.arrayBuffer();
                    const pdf = await pdfjsLib.getDocument({data: arrayBuffer}).promise;
                    const filePages = pdf.numPages;
                    totalPages += filePages;
                    
                    // 将当前文件的所有页面转换为图片
                    for (let pageNum = 1; pageNum <= filePages; pageNum++) {
                        const page = await pdf.getPage(pageNum);
                        const scale = 2;
                        const viewport = page.getViewport({scale});
                        const aspectRatio = viewport.width / viewport.height;

                        const canvas = document.createElement('canvas');
                        const ctx = canvas.getContext('2d');
                        canvas.width = viewport.width;
                        canvas.height = viewport.height;
                        await page.render({canvasContext: ctx, viewport}).promise;

                        const dataURL = canvas.toDataURL('image/png');
                        const base64Data = dataURL.split(',')[1];
                        const binaryString = atob(base64Data);
                        const bytes = new Uint8Array(binaryString.length);
                        for (let j = 0; j < binaryString.length; j++) {
                            bytes[j] = binaryString.charCodeAt(j);
                        }
                        
                        pdfImages.push({
                            imageData: bytes.buffer,
                            aspectRatio: aspectRatio,
                            fileName: pdfFile.name
                        });
                        
                        processedPages++;
                        // 更新进度条（转换图片阶段占60%）
                        const progress = Math.round((processedPages / totalPages) * 60);
                        progressBar.style.width = progress + '%';
                        progressBar.textContent = progress + '%';
                    }
                }
                
                // 生成Word文档
                statusDiv.textContent = '正在生成Word文档...';
                statusDiv.className = 'p-4 rounded-lg bg-blue-100 text-blue-800 border border-blue-200';
                
                // 创建Word文档
                const doc = new docx.Document({
                    creator: "PDF转Word工具",
                    description: "由多个PDF生成的Word文档",
                    title: "合并PDF文档",
                    styles: {
                        paragraphStyles: [
                            {
                                id: "Normal",
                                name: "Normal",
                                run: {
                                    size: 24,
                                },
                                paragraph: {
                                    spacing: {
                                        line: 276,
                                    },
                                },
                            },
                            {
                                id: "Heading1",
                                name: "Heading 1",
                                run: {
                                    size: 36,
                                    bold: true,
                                },
                                paragraph: {
                                    spacing: {
                                        before: 240,
                                        after: 120,
                                    },
                                },
                            },
                        ],
                    },
                    numbering: {
                        config: []
                    },
                    sections: []
                });
                
                // 设置图片固定高度为16cm（1cm = 56.7 dxa）
                const fixedHeight = 16 * 56.7; // 16cm转换为dxa单位
                
                // 添加每个PDF文件的内容
                let currentFileName = '';
                
                for (let i = 0; i < pdfImages.length; i++) {
                    const { imageData, aspectRatio, fileName } = pdfImages[i];
                    const calculatedWidth = fixedHeight * aspectRatio; // 保持纵横比的宽度
                    
                    // 如果是新文件的第一页，添加文件名作为标题
                    if (fileName !== currentFileName) {
                        currentFileName = fileName;
                        
                        const titleParagraph = new docx.Paragraph({
                            text: currentFileName,
                            style: "Heading1",
                        });
                        
                        doc.addSection({
                            properties: {
                                page: {
                                    size: {
                                        width: 11906, // A4宽度(21cm)
                                        height: 16838, // A4高度(29.7cm)
                                        orientation: docx.PageOrientation.PORTRAIT
                                    },
                                    margins: {
                                        top: 1440,
                                        bottom: 1440,
                                        left: 1440,
                                        right: 1440,
                                    }
                                }
                            },
                            children: [titleParagraph]
                        });
                    }
                    
                    // 更新进度（生成Word阶段占40%）
                    const progress = 60 + Math.round((i / pdfImages.length) * 40);
                    progressBar.style.width = progress + '%';
                    progressBar.textContent = progress + '%';
                    
                    // 创建图片段落
                    const imageRun = new docx.ImageRun({
                        data: imageData,
                        transformation: {
                            width: calculatedWidth,
                            height: fixedHeight,
                            flip: null,
                        }
                    });
                    
                    const paragraph = new docx.Paragraph({
                        children: [imageRun],
                        spacing: {
                            after: 400,
                        }
                    });
                    
                    // 添加section到文档
                    doc.addSection({
                        properties: {
                            page: {
                                size: {
                                    width: 11906, // A4宽度(21cm)
                                    height: 16838, // A4高度(29.7cm)
                                    orientation: docx.PageOrientation.PORTRAIT
                                },
                                margins: {
                                    top: 1440,
                                    bottom: 1440,
                                    left: 1440,
                                    right: 1440,
                                }
                            }
                        },
                        children: [
                            paragraph,
                            ...(i < pdfImages.length - 1 ? [new docx.Paragraph({
                                children: [new docx.PageBreak()]
                            })] : [])
                        ]
                    });
                }
                
                // 生成并下载Word文档
                const blob = await docx.Packer.toBlob(doc);
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = '合并PDF文档.docx';
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
                
                // 完成
                progressBar.style.width = '100%';
                progressBar.textContent = '100%';
                statusDiv.textContent = `✅ 转换完成！共处理 ${pdfFiles.length} 个文件，${pdfImages.length} 页。`;
                statusDiv.className = 'p-4 rounded-lg bg-green-100 text-green-800 border border-green-200';
                
            } catch (error) {
                progressContainer.classList.add('hidden');
                statusDiv.textContent = `❌ 转换失败: ${error.message}`;
                statusDiv.className = 'p-4 rounded-lg bg-red-100 text-red-800 border border-red-200';
                statusDiv.classList.remove('hidden');
                console.error(error);
            }
        }
    </script>
</body>
</html>
